let path = require('path');
let fs = require('fs');
let vm = require('vm');

// Module类
function Module(id) {
    this.id = id;
    this.exports = {};
}

Module.wrap = function(script) {
    return `(function (exports, require, module, __filename, __dirname) {
        ${script}
    })`
}

Module._extensions = {
    '.js'(module) {
        // 读取文件的同步方法
        let content = fs.readFileSync(module.id, 'utf8');
        let fnStr = Module.wrap(content);
        let fn = vm.runInThisContext(fnStr);
        fn.call(module.exports, module.exports, req, module)
    },
    '.json'(module) {
        let content = fs.readFileSync(module.id,'utf8');
        module.exports = JSON.parse(content);    
    }
}

Module._resolveFilename = function(path) {
    let ext = Object.keys(Module._extensions);
    for (let p of ext) {
        try {
            fs.accessSync(`${path}${p}`);
            return `${path}${p}`
        } catch {

        }
    }
}

function req(p) {
    let realPath = path.resolve(__dirname, p);
    lastPath = Module._resolveFilename(realPath);
    let module = new Module(lastPath);
    // 可以拿到文件的扩展名
    let extName = path.extname(lastPath);
    Module._extensions[extName](module);
    return module.exports;
}

let r = req('./test');

console.log(r)
